import lib from './ThreeLib.js'
import { Color } from 'https://unpkg.com/three/build/three.module.js';

const defAttr = () => ({
    gl: null,
    list: {},
    types: [
        "POINTS",
        "TRIANGLES", "TRIANGLE_STRIP", "TRIANGLE_FAN",
        "LINES", "LINE_STRIP", "LINE_LOOP",
    ],
    count: 0,
})

export default class Poly {
    constructor(attr) {
        Object.assign(this, defAttr(), attr);
        this.init();
    }

    init() {
        const { gl } = this;
        if (!gl) {
            console.log("gl is null!");
        }
    }

    createBuffer(attrName, size, curarr = []) {
        const { gl, list } = this;
        //绑定缓冲对象
        gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
        //写入数据
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(curarr), gl.STATIC_DRAW);
        //获取attribute 变量
        const obj = gl.getAttribLocation(gl.program, attrName);
        //修改attribute 变量
        gl.vertexAttribPointer(obj, size, gl.FLOAT, false, 0, 0);
        //赋能-批处理
        gl.enableVertexAttribArray(obj);

        list[attrName] = { arr: curarr, size: size };

        if (attrName == 'a_Position') {
            this.count = curarr.length / size;
        }
    }

    updataArr(attrName, arr) {
        const { list } = this;
        if (!list[attrName]) {
            console.log("ex!")
            return;
        } else {
            var temp = list[attrName];
            list[attrName] = { arr: arr, size: temp.size };
            this.updateBuffer(attrName);

            if (attrName == 'a_Position') {
                this.count = arr.length / list[attrName].size;
            }
        }
    }

    updateBuffer(attrName) {
        const { gl, list } = this;
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(list[attrName].arr), gl.STATIC_DRAW);
    }

    getArr() {
        return this.list;
    }

    draw(types = this.types) {
        const { gl, count } = this;
        lib.clearCanvas(gl, new Color("rgba(0,0,0,1)"), 1);
        for (let type of types) {
            gl.drawArrays(gl[type], 0, count);
        }
    }
}